<?php
/**
 * Created by PhpStorm.
 * User: lcz
 * Date: 2018/4/3
 * Time: 9:15
 * 商品控制器
 */
namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\Elasticsearch;
use app\common\model\GoodsGroup;
use app\common\model\OrderGroup;
use app\common\model\SearchCount;
use app\common\model\SupplyChain;
use app\common\model\UserSearch;
use think\Cache;
use think\Db;

class Goods extends Api{
	protected $noNeedLogin = ['*'];
	protected $noNeedRight = ['*'];
	
	/**
	 * 商品详情
	 */
	public function detail(){
		$id = input('post.id');
		if(!$id || $id <0){
			$this->error('参数错误');
		}
		
		$goods = Db::name('goods')->alias('g')
			->join('brand b', 'g.brand_id = b.id', 'left')
			->join('business bu', 'g.business_id = bu.id', 'left')
			->field('b.name as brand_name, g.goods_name, g.market_price, g.shop_price, exchange_integral, g.sale_number,  g.store_count, g.original_image, g.business_id, bu.name as business_name, g.content,g.goods_remark, g.click_count, g.id, g.chain_no, g.goods_type, g.use_day, g.send_number, g.send_day, g.open_user_grade, use_point as point, give_balance as sendmoney')
			->where([
				'g.id' => $id,
				'g.is_on_sale' => 1,
				'g.effective_time' => ['elt', time()]
			])
			->find();
		if(!$goods) {
			$this->error('商品不存在或已下架', Db::name('goods')->getLastSql());
		}
		
		//获取商品相册
		$imgRow = Db::name('goodsImages')->where(['goods_id' => $id])->field('image_url')->select();
		//主图做为相册的第一张
		$images[] = ['image_url' => $goods['original_image']];
		$images = array_merge($images, $imgRow);
		$goods['imgArray'] = array_values($images);
		
		//获取属性
		$attrRow = Db::name('goodsAttrValue')->alias('av')
			->join('goodsAttribute a', 'av.attr_id = a.id', 'left')
			->where(['av.goods_id' => $id])
			->field('a.name, av.value')
			->select();
		
		$goods['attr'] = $attrRow;
		
		//获取规格
		$specPrice = Db::name('goodsSpecPrice')
			->where(['goods_id' => $id])
			->select();
		
		$spec = [];
		if($specPrice){
			//自己商城的规格
			if(!$goods['chain_no']){
				$itemIds = [];
				foreach ($specPrice as $item){
					$ids = explode('_',$item['key']);
					$itemIds = array_unique(array_filter(array_merge($itemIds, $ids)));
				}
				
				if($itemIds){
					$specItem = Db::name('specItem')->alias('i')
						->join('spec s', 's.id = i.spec_id', 'left')
						->where(['i.id' => ['in', $itemIds]])
						->field('s.id as spec_id, s.name as spec_name, i.id, i.name')
						->select();
					if($specItem){
						foreach ($specItem as $value){
							if(isset($spec[$value['spec_id']])){
								$spec[$value['spec_id']]['items'][] = [
									'id' => $value['id'],
									'value' => $value['name']
								];
							} else {
								$spec[$value['spec_id']] = [
									'name' => $value['spec_name'],
									'items' => [
										[
											'id' => $value['id'],
											'value' => $value['name']
										]
									]
								];
							}
						}
					}
				}
			} else {
				//供应链的规格
				$supply = new SupplyChain();
				$specRes = $supply->goodsSpec($goods['chain_no']);
				if($specRes['status']) {
					$spec = $specRes['data'];
				}
			}
			
			
		}
		
		$goods['spec'] = array_values($spec);
		$goods['specPrice'] = $specPrice;
		
		//获取评价
		$comments = Db::name('goodsComment')->alias('c')
			->join('user u','u.id = c.user_id','left')
			->where(['c.goods_id' => $id])
			->limit(5)
			->field('u.username,c.images, u.avatar as icon, c.content, c.score,c.create_time, c.is_anonymous')
			->select();
		
		$commentsCount = Db::name('goodsComment')
			->where(['goods_id' => $id])
			->field('count(id) as count, avg(score) as average')
			->find();
		if($comments){
			foreach ($comments as $key => $comment){
				$comments[$key]['create_time'] = date('Y-m-d',$comment['create_time']);
				$comments[$key]['images'] = array_filter(explode(',',$comment['images']));
				if($comment['is_anonymous']){
					$comments[$key]['username'] = mb_substr($comment['username'],0,3,'utf8').'***';
				}
			}
		}
		
		
		$goods['favorite'] = 0;
		
		if($this->auth->id){
			//判断是否已经收藏
			$favoriteModel = new \app\common\model\Favorite();
			$favorite = $favoriteModel->where(['relation_id' => $id, 'user_id' => $this->auth->id, 'status' => $favoriteModel::STATUS_Y, 'type' => $favoriteModel::TYPE_GOODS])->find();
			if($favorite){
				$goods['favorite'] = 1;
			}
		}
		
		//浏览加1
		Db::name('goods')->where(['id' => $id])->setInc('click_count');
		
		$goods['comments'] = [
			"count" =>  $commentsCount['count'],
			"average" => ceil($commentsCount['average']/5*100)/100,
            "data" => $comments,
		];
		
		//商品页面详情URL
		$goods['url'] = $this->request->domain().url('/mobile/goods/appDetail',['id' => $id]);
		$goods['share_url'] = $this->request->domain().url('/mobile/goods/detail',['id' => $id, 'rmobile' => $this->auth->mobile]);
		
		//判断是否拼团商品
		$groupSetting = Db::name('goodsGroup')
			->where(['goods_id' => $id, 'status' => GoodsGroup::STATUS_Y])
			->field('id, price, number, limit_minute')
			->find();
		
		$goods['active_type'] = 'normal';
		
		if($groupSetting) {
			//如果有拼团商品，查找拼团的信息
			$groupOrder = Db::name('orderGroup')->alias('o')
				->join('user u', 'o.user_id = u.id', 'left')
				->where(['o.goods_group_id' => $groupSetting['id'], 'o.status' => OrderGroup::STATUS_W])
				->field('o.id as order_group_id, u.username, u.avatar, o.limit_number, o.buy_number, o.end_time')
				->select();
			
			$groupSetting['order'] = $groupOrder;
			//商品活动类型为拼团商品
			$goods['active_type'] = 'group';
		} else {
			$groupSetting['order'] = [];
		}
		$goods['group_info'] = $groupSetting;
		
		//判断是否秒杀商品
		$spikeSetting = Db::name('goodsSpike')
			->where(['goods_id' => $id, 'start_time' => ['lt', time()], 'end_time'=>['gt', time()]])
			->field('id, store_number, price, limit_number, buy_number, end_time')
			->find();
		if($spikeSetting && $spikeSetting['store_number'] > $spikeSetting['buy_number']) {
			$goods['active_type'] = 'spike';
			$spikeSetting['progressbar'] = ceil($spikeSetting['buy_number']/$spikeSetting['store_number']*10000)/100;
			$goods['spike_info'] = $spikeSetting;
		}
		
		$goodsModel = new \app\common\model\Goods();
		$goods['tags'] = $goodsModel->getGoodsTags($goods['goods_type'], $goods['open_user_grade']);
		
		$this->success('查询成功',$goods);
	}
	

	
	/**
	 * 搜索商品
	 */
	public function search(){
		//搜索内容
		$keyword = input('post.keyword');
		
		
		$ip = $_SERVER["REMOTE_ADDR"];
		
		$userId = $this->auth->id;
		
		$page = input('post.page', 1, 'int');
		
		//添加用户搜索记录
		$userSearchModel = new UserSearch();
		$userSearchModel->addRecord($keyword, $userId, $ip);
		
		//添加搜索总记录
		$countModel = new SearchCount();
		$countModel->addRecord($keyword);
		
		//搜索商品
		$goodsModel = new \app\common\model\Goods();
		$el = new Elasticsearch();
		$data = [
			'query' => [
				'multi_match' => [
					'query' => $keyword,
					'fields' => ["goods_name", "goods_remark"]
				]
			]
		];
		$elres = $el->search($data);
		$res = json_decode($elres, true);
		if(isset($res['hits']['total']) && $res['hits']['total'] > 0){
			$elGoods = $res['hits']['hits'];
			foreach($elGoods as $v){
				$ids[] = $v['_id'];
			}
			
			$where['id'] = ['in', $ids];
		} else {
			$where = '(goods_name like \'%'.$keyword.'%\') or (keywords like \'%'.$keyword.'%\') and is_on_sale = 1 and \'effective_time\' <= '.time();
		}
		
		$goods = Db::name('goods')
			->where($where)
			->order(['sort' => 'ASC'])
			->field('id, goods_name, original_image, shop_price, market_price, sale_number, exchange_integral, use_point as point, give_balance as sendmoney')
			->page($page)
			->select();
		
		$this->success('查询成功', $goods);
	}
	
	
	/**
	 * 热门搜索
	 */
	public function hotSearch(){
		$page = input('page');
		
		$data = Db::name('searchCount')
			->order(['numbers' => 'DESC'])
			->page($page, 50)
			->column('keyword','id');
		
		$returnData = [];
		if($data) {
			$n = ceil(count($data)/10);
			for($i = 0; $i<$n; $i++) {
				$returnData[] = array_splice($data,0,10);
			}
		}
		$this->success('查询成功', $returnData);
	}
	
	
	/**
	 * 商品评价列表
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
	public function goodsComments(){
		$id = input('post.id', '', 'int');
		$page = input('post.page', 1, 'int');
		
		//获取评价
		$comments = Db::name('goodsComment')->alias('c')
			->join('user u','u.id = c.user_id','left')
			->where(['c.goods_id' => $id])
			->page($page)
			->field('u.username,  u.avatar as icon, c.images, c.content, c.score,c.create_time, c.is_anonymous')
			->select();
		
		$commentsCount = Db::name('goodsComment')
			->where(['goods_id' => $id])
			->field('count(id) as count, avg(score) as average')
			->find();
		
		if($comments){
			foreach ($comments as $key => $comment){
				$comments[$key]['create_time'] = date('Y-m-d',$comment['create_time']);
				$comments[$key]['images'] = explode(',',$comment['images']);
				if($comment['is_anonymous']){
					$comments[$key]['username'] = mb_substr($comment['username'],0,3,'utf8').'***';
				}
			}
		}
		
		$returnData  = [
			"count" =>  $commentsCount['count'],
			"average" => ceil($commentsCount['average']/5*100)/100,
			"data" => $comments,
		];
		
		$this->success('查询成功', $returnData);
	}
	
	/**
	 * 小能客服查询商品详情
	 * @id 商品ID
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
	public function talkDetail(){
		$id = input('id');
		$cacheName = 'Goods/talkDetail/id/'.$id;
		if(!$returnData = Cache::get($cacheName)) {
			$returnData = [
				'item' => [
					'id' => $id, //商品ID
					'name' => '',//商品名称
					'imageurl' => '',//商品图片地址(全路径)
					'url' => '',//商品详情页地址
					'currency' => '￥',//货币符号
					'siteprice' => '',//商品网站价格(和currency合并显示，显示效果￥：180.00)
					'marketprice' => '',//商品市场价格
					'category' => '',//商品分类名称
					'brand' => '',//商品品牌名称
				]
			];
			
			$data = Db::name('goods')->alias('g')
				->join('goodsCategory c', 'g.category_id = c.id', 'left')
				->join('brand b', 'b.id = g.brand_id', 'left')
				->where(['g.id' => $id])
				->field('g.id, g.goods_name as name, g.original_image as imageurl, g.shop_price as siteprice, g.market_price as marketprice, c.name as category, b.name as brand')
				->find();
			if($data){
				foreach ($data as $k => $v){
					$item[$k] = (string) $v;
				}
				$item["currency"] = "￥";
				$item['url'] = $this->request->domain().url('/mobile/goods/appDetail',['id' => $id]);
				$returnData['item'] = $item;
			}
			
			Cache::set($cacheName, $returnData, 600);
		}
		
		
		echo json_encode($returnData);
		die;
	}
	
	
	/**
	 * 拼团商品
	 */
	public function groupGoods(){
		$page = input('post.page', 1, 'intval');
		
		$goods = Db::name('goodsGroup')->alias('gg')
			->join('goods g', 'gg.goods_id = g.id', 'left')
			->where([
				'gg.status' => GoodsGroup::STATUS_Y,
				'g.is_on_sale' => \app\common\model\Goods::IS_ON_SALE_Y,
				'g.effective_time' => ['elt', time()]
			])
			->field('gg.goods_id, gg.price as group_price, gg.number, gg.success_number, g.goods_name, g.original_image, g.shop_price')
			->order(['gg.success_number' => 'DESC'])
			->page($page)
			->select();
		
		$this->success('查询成功', $goods);
	}
	
	
	/**
	 * 秒杀时间
	 */
	public function spikeTime(){
		$startTime = strtotime(date('Y-m-d 00:00:00'));
		$endTime = strtotime(date('y-m-d 00:00:00', strtotime('+1 days')));
		
		$times = Db::name('goodsSpike')
			->where(['start_time' => [['gt',$startTime], ['elt', $endTime]]])
			->group('start_time')
			->column('from_unixtime(start_time, "%H:%i") as start_time', 'id');
		$nowDate = date('H:00');
		if($times) {
			foreach($times as $k => $time) {
				$active = 0;
				if($time == $nowDate) {
					$name = '抢购中';
					$active = 1;
				} elseif($time < $nowDate) {
					$name = '已开始';
				} else {
					$name = '即将开始';
				}
				$times[$k] = [
					'time' => $time,
					'name' => $name,
					'goods' => [],
					'active' => $active
				];
			}
		}
		
		
		$this->success('查询成功', array_values($times));
	}
	
	/**
	 * 秒杀商品
	 */
	public function spikeGoods(){
		$page = input('post.page', 1, 'intval');
		$time = input('post.date_time') ? : date('H:00');
		$dateTime = strtotime(date('Y-m-d ').$time.':00');
		
		$goods = Db::name('goodsSpike')->alias('gs')
			->join('goods g', 'gs.goods_id = g.id', 'left')
			->where([
				'gs.start_time' => $dateTime,
				'g.is_on_sale' => \app\common\model\Goods::IS_ON_SALE_Y,
				'g.effective_time' => ['elt', time()]
			])
			->field('gs.goods_id, gs.price as group_price, gs.store_number, gs.buy_number, g.goods_name, g.original_image, g.shop_price, 0 as progressbar, gs.start_time')
			->order(['gs.buy_number' => 'DESC'])
			->page($page)
			->select();
		
		if($goods) {
			foreach ($goods as $k => $v) {
				$goods[$k]['progressbar'] = ceil($v['buy_number']/$v['store_number']*10000)/100;
				
				//如果开始时间小于当前时间，状态为已开始
				if($v['start_time'] < time()) {
					$goods[$k]['status'] = true;
				} else {
					$goods[$k]['status'] = false;
				}
			}
		}
		
		$this->success('查询成功', array_values($goods));
	}
}
